<template>
  <div class="app-container org">
    <el-card>
      <el-row>
        <el-col :span="24">
          <p class="pinformation">搜索条件</p>
        </el-col>
      </el-row>
      <el-form ref="queryRef" label-width="100" :model="queryParams">
        <el-row>
          <el-col :span="3">
            <el-form-item label="类型：" prop="drugType" label-width="50">
              <el-select placeholder="请选择" clearable v-model="queryParams.drugType" filterable @change="handleQuery">
                <el-option v-for="dict in proxy.addListNoLimit(sys_drug_type)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="药品名称：" prop="drugName" label-width="80">
              <el-input clearable maxlength="100" @keyup.enter="handleQuery" placeholder="请输入药品名称"
                v-model="queryParams.drugName" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="质量等级：" prop="qualityLevel" label-width="80">
              <el-select placeholder="请选择" clearable v-model="queryParams.qualityLevel" filterable>
                <el-option v-for="dict in proxy.addListNoLimit(sys_drug_quality_level)" :key="dict.value"
                  :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="备案证明编号：" prop="code" label-width="110">
              <el-input clearable maxlength="100" placeholder="请输入" @keyup.enter="handleQuery"
                v-model="queryParams.code" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="销售单位：" prop="saleFactory" label-width="80">
              <el-input @keyup.enter="handleQuery" clearable maxlength="100" placeholder="请输入销售单位"
                v-model="queryParams.saleFactory" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="生产厂家：" prop="produceFactory" label-width="80">
              <el-input clearable maxlength="100" @keyup.enter="handleQuery" placeholder="请输入生产厂家"
                v-model="queryParams.produceFactory" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="状态：" prop="stepId" label-width="50">
              <el-select placeholder="请选择" clearable v-model="queryParams.stepId" filterable>
                <el-option v-for="dict in proxy.addListNoLimit(sys_drug_step)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-row justify="end">
              <el-button type="success" @click="handleQuery">搜索</el-button>
              <el-button class="resetBtn" @click="resetQuery">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <p class="pinformation">化学药品入库记录列表</p>
        <p class="totalStyle">共 {{ total }} 条数据</p>
        <el-button type="success" link icon="Plus" @click="singleAdd"
          style="margin-left: 40px; margin-bottom: 5px">单个入库</el-button>
        <el-row style="padding-bottom: 5px">
          <el-button type="success" link icon="Plus" style="margin-left: 20px" @click="importTemplate">导出数据</el-button>
          <el-button type="success" link icon="Plus" style="margin-left: 20px">批量入库</el-button>
          <el-button type="success" link icon="Plus" style="margin-left: 20px" @click="handleExport">导出入库记录</el-button>
          <el-button type="success" style="margin-left: 10px" link icon="Plus" @click="handleImport">导入入库记录</el-button>
        </el-row>
        <el-table ref="mainTableRef" :data="bzwzTable" @selection-change="handleSelChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="唯一性编号" prop="drugCode" align="center" />
          <el-table-column label="化学药品名称" prop="drugName" align="center" />
          <el-table-column label="类型" prop="drugType" align="center">
            <template #default="scope">
              <dict-tag :options="sys_drug_type" :value="scope.row.drugType" />
            </template>
          </el-table-column>
          <el-table-column label="质量等级" prop="qualityLevel" align="center">
            <template #default="scope">
              <dict-tag :options="sys_drug_quality_level" :value="scope.row.qualityLevel" />
            </template>
          </el-table-column>
          <el-table-column label="销售单位" prop="saleFactory" align="center" />
          <el-table-column label="生产厂商" prop="produceFactory" align="center" />
          <el-table-column label="备案证明编号" prop="code" align="center" />
          <el-table-column label="规格" prop="totalGg" align="center">
            <template #default="scope">
              {{ scope.row.totalGg }}
              <span v-html="transformation(scope.row.ggUnitName)"></span>
            </template>
          </el-table-column>
          <el-table-column label="保存位置" prop="saveLocation" align="center" />
          <el-table-column label="入库日期" prop="createDate" align="center" />
          <el-table-column label="入库数量" prop="createCount" align="center">
            <template #default="scope">
              <span style="color: var(--theme-deep-color)"> {{ scope.row.createCount }}</span>
              <!-- <el-button link @click="jcxmCountClick(scope.row.drugId)">{{
                  }}</el-button> -->
            </template>
          </el-table-column>
          <el-table-column label="入库人" prop="drugAdminId" align="center">
            <template #default="scope">
              {{
                proxy.getItemByArray(
                  userList,
                  "userId",
                  scope.row.drugAdminId,
                  "nickName"
                )
              }}
            </template>
          </el-table-column>
          <el-table-column label="保管人1" prop="drugAdminOneId" align="center">
            <template #default="scope">
              {{
                proxy.getItemByArray(
                  userList,
                  "userId",
                  scope.row.drugAdminOneId,
                  "nickName"
                )
              }}
            </template>
          </el-table-column>
          <el-table-column label="保管人2" prop="drugAdminOneId" align="center">
            <template #default="scope">
              {{
                proxy.getItemByArray(
                  userList,
                  "userId",
                  scope.row.drugAdminTwoId,
                  "nickName"
                )
              }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="stepId">
            <template #default="scope">
              <dict-tag :options="sys_drug_step" :value="scope.row.stepId" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="success" @click="xqBzwz(scope.row.drugId, 1)">引用</el-button>
              <el-button link type="success" @click="xqBzwz(scope.row.drugId, 3)">编辑</el-button>
              <el-button link type="success" @click="delHxyp(scope.row.drugId)" v-if="!scope.row.outCount">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-row>
    </el-card>
    <!-- 点击行内检测项目数的弹窗 -->
    <!-- <el-dialog :class="'el-dialog-theme3'"
          append-to-body
          draggable
          :close-on-click-modal="false"
          v-model="jcxmOpen"
          @close="closedDialog"
          :title="title"
        >
          <el-row>
            <el-col :span="3">
              <p class="pinformation">检测项目列表</p>
            </el-col>
            <el-col :span="10">
              <p class="totalStyle">共 {{ multiplexTable.length }} 条数据</p>
            </el-col>
          </el-row>
          <el-table :data="multiplexTable">
            <el-table-column label="检测项目" prop="bucketId" align="center">
              <template #default="scope">
                <span
                  v-html="transformation(getJcxmName(scope.row.bucketId))"
                ></span>
              </template>
            </el-table-column>
            <el-table-column label="浓度值" prop="con" align="center" />
            <el-table-column label="浓度值单位" prop="conUnit" align="center">
              <template #default="scope">
                <span
                  v-html="transformation(getUnitName(scope.row.conUnit))"
                ></span>
              </template>
            </el-table-column>
            <el-table-column label="不确定度值" prop="notvalue" align="center" />
            <el-table-column
              label="不确定度单位"
              prop="notvalueUnit"
              align="center"
            >
              <template #default="scope">
                <span
                  v-html="transformation(getUnitName(scope.row.notvalueUnit))"
                ></span>
              </template>
            </el-table-column>
          </el-table>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="danger" @click="jcxmOpen = false">关 闭</el-button>
            </div>
          </template>
        </el-dialog> -->
    <!-- 单个入库和引用弹窗 -->
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="rkOrYyOpen" :title="rkOrYyTitle" @close="dialogClose" v-if="rkOrYyOpen" width="1100">
      <el-form label-width="110" ref="rkOrYyRef" :model="form" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="药品类型：" prop="drugType">
              <el-select placeholder="请选择" clearable v-model="form.drugType" filterable @change="drugTypeChange"
                style="width: 100%" v-if="!form.drugId">
                <el-option v-for="dict in sys_drug_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
              <span v-else><dict-tag :options="sys_drug_type" :value="form.drugType" /></span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="药品名称：" prop="drugName">
              <el-input clearable maxlength="100" v-model="form.drugName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="唯一性编号：">
              <onlinePreview :typeId="serialTypeId" @emitForm="emitForm" ref="onlinePreviewRef" v-if="!form.drugCode">
              </onlinePreview>
              <span v-else>{{ form.drugCode }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库数量：" prop="createCount">
              <el-input-number clearable style="width: 100%" controls-position="right" :disabled="(form.outCount ? true : false) && form.outCount !== 0
                " :min="1" v-model="form.createCount"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-row :gutter="10">
              <el-col :span="15">
                <el-form-item label="规格：" prop="totalGg">
                  <el-input-number :min="1" clearable style="width: 100%" v-model="form.totalGg" controls-position="right"
                    :disabled="(form.useGg ? true : false) && form.useGg !== 0"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item prop="ggUnit" label-width="0">
                  <el-select v-model="form.ggUnit" placeholder="" clearable filterable>
                    <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item.unitId">
                      <span v-html="transformation(item.unitName)"></span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备案证明编号：" prop="code">
              <el-input clearable maxlength="100" placeholder="请输入" v-model="form.code"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="销售单位：" prop="saleFactory">
              <el-input clearable maxlength="100" v-model="form.saleFactory"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产单位：" prop="produceFactory">
              <el-input clearable maxlength="100" v-model="form.produceFactory"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保存位置：" prop="saveLocation">
              <el-input clearable maxlength="100" v-model="form.saveLocation"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库人：" prop="drugAdminId">
              <el-select v-model="form.drugAdminId" filterable clearable style="width: 100%">
                <el-option v-for="item in userList" :value="item.userId" :key="item.userId"
                  :label="item.nickName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库日期：" prop="createDate">
              <el-date-picker style="width: 100%" v-model="form.createDate" placeholder="请选择入库日期" type="date"
                value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质量等级：" prop="qualityLevel">
              <el-select placeholder="请选择" clearable v-model="form.qualityLevel" filterable style="width: 100%">
                <el-option v-for="dict in sys_drug_quality_level" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="保管人1：" prop="drugAdminOneId">
              <el-select v-model="form.drugAdminOneId" filterable clearable style="width: 100%">
                <el-option v-for="item in userList" :value="item.userId" :key="item.userId"
                  :label="item.nickName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保管人2：" prop="drugAdminTwoId">
              <el-select v-model="form.drugAdminTwoId" filterable clearable style="width: 100%">
                <el-option v-for="item in userList" :value="item.userId" :key="item.userId"
                  :label="item.nickName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="saveHcyp">保 存</el-button>
          <el-button type="danger" @click="rkOrYyOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" :title="upload.title" v-model="upload.open" width="400px"
      append-to-body draggable :close-on-click-modal="false">
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-error="handleUploadError"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="success" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitFileForm">确 定</el-button>
          <el-button type="danger" @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BzwzOutin">
import onlinePreview from "@/components/onlinePreview/index.vue";
import {
  listLedger,
  delHxypList,
  hxypViewForm,
  addHxyp,
} from "@/api/resource/hxyp";
import { getCurrentTime, getCurrentUser } from "@/api/common";
import { getSeqId } from "@/api/common";
import { getUnitList } from "@/api/store/unit";
import { listUser } from "@/api/contract/check";

const { proxy } = getCurrentInstance();
const { sys_drug_type, sys_drug_quality_level, sys_drug_step } = proxy.useDict(
  "sys_drug_type",
  "sys_drug_quality_level",
  "sys_drug_step"
);

const bzwzTable = ref([]);
const multiplexTable = ref([]);
const jcxmOpen = ref(false);
const rkOrYyOpen = ref(false);
const rkOrYyTitle = ref("");
const useOpen = ref(false);
const title = ref("查看检测项目");
const statusList = ref([{ value: 1, label: "不限" }]);
const serialTypeId = ref();
const onlinePreviewRef = ref(null);
function emitForm(val) {
  form.value.params["serialData"] = val;
}
const data = reactive({
  form: { params: {} },
  queryParams: {
    pageNum: 1, // 当前页数
    pageSize: 10, // 当前页数据条数
    drugType: -1,
    qualityLevel: -1,
    stepId: -1,
  },
  rules: {
    drugType: [
      { required: true, message: "药品类型不能为空", trigger: "blur" },
    ],
    createCount: [
      { required: true, message: "入库数量不能为空", trigger: "blur" },
    ],
    drugName: [
      { required: true, message: "药品名称不能为空", trigger: "blur" },
    ],
    code: [
      { required: true, message: "备案证明编号不能为空", trigger: "blur" },
    ],
    totalGg: [{ required: true, message: "规格数量不能为空", trigger: "blur" }],
    ggUnit: [{ required: true, message: "规格单位不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

const heightParams = ref([{ tableName: "main", bottomHeight: 21 }]);

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

const total = ref(0);
const dateRange = ref([]);
function getList() {
  listLedger(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      bzwzTable.value = res.rows;
      total.value = res.total;
    }
  );
}
getList();

function handleQuery() {
  dateRange.value = [];
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// function jcxmCountClick(row) {
//   bzwzList({ bzwzId: row }).then((res) => {
//     multiplexTable.value = res.data;
//     jcxmOpen.value = true;
//   });
// }

function closedDialog() {
  multiplexTable.value = [];
}

function delHxyp(drugId) {
  proxy.$modal
    .confirm("是否确认删除该条记录？")
    .then(function () {
      delHxypList(drugId).then((res) => {
        proxy.$modal.msgSuccess("删除成功");
        getList();
      });
    })
    .catch(() => { });
}

function xqBzwz(drugId, isOpen) {
  hxypViewForm(drugId).then((res) => {
    form.value = res.data;
    rkOrYyOpen.value = true;
    if (isOpen == 1) {
      rkOrYyTitle.value = "引用化学药品";
      delete form.value.outCount;
      delete form.value.drugId;
      delete form.value.drugCode;
      form.value.params = {};
      drugTypeChange(form.value.drugType);
    } else if (isOpen == 3) {
      rkOrYyTitle.value = "编辑化学药品";
    }
  });
}

function singleAdd() {
  getCurrentTime().then((res) => {
    form.value.createDate = res.data;
  });
  getCurrentUser().then((res) => {
    form.value.drugAdminId = res.data;
    form.value.drugAdminOneId = res.data;
    form.value.drugAdminTwoId = res.data;
  });
  rkOrYyOpen.value = true;
  rkOrYyTitle.value = "化学药品入库";
  serialTypeId.value = -1;
  nextTick(() => {
    form.value.params = {};
    onlinePreviewRef.value.reset();
  });
}

function saveHcyp() {
  proxy.$refs["rkOrYyRef"].validate((valid) => {
    if (valid) {
      if (!form.value.drugId && !form.value.params["serialData"]) {
        proxy.$modal.msgError("唯一性编号不能为空");
        return false;
      }
      addHxyp(form.value).then((res) => {
        rkOrYyOpen.value = false;
        proxy.$modal.msgSuccess(res.msg);
        getList();
      });
    }
  });
}

const unitList = ref([]);
getUnitList().then((res) => {
  unitList.value = res.data;
});

function handleSelChange(selection) {
  multiplexTable.value = selection;
}

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 21 }];
    }
    getTableHeight();
  }
);

function transformation(row) {
  const a = proxy.getSupAndSub(row);
  return a;
}

const userList = ref([]);
listUser().then((res) => {
  userList.value = res.data;
});

watch(
  () => rkOrYyOpen.value,
  () => {
    if (rkOrYyOpen.value == false) {
      form.value = {};
    }
  }
);

function dialogClose() {
  serialTypeId.value = -1;
  form.value.params = {};
}

function drugTypeChange(row) {
  if (row == "") {
    serialTypeId.value = -1
  }
  if (row === 0) serialTypeId.value = 34;
  if (row === 1) serialTypeId.value = 35;
  // if (row === 2) serialTypeId.value = 36;
}

// -------------------导入模板逻辑-------------------
import { getToken } from "@/utils/auth";
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/resource/drug/importData",
});

/** 导入按钮操作 */
function handleImport() {
  upload.title = "化学药品入库登记导入";
  upload.open = true;
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    response.msg +
    "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "/resource/drug/export",
    {
      ...queryParams.value,
    },
    `化学药品入库登记表_${new Date().getTime()}.xlsx`
  );
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "/resource/drug/importTemplate",
    {},
    `化学药品模板_${new Date().getTime()}.xlsx`
  );
}

// 上传失败
function handleUploadError(err) {
  upload.isUploading = false;
  proxy.$modal.msgError("导入数据失败，原因：" + err.message);
}
</script>

<style lang="scss" scoped>
.el-radio {
  margin-right: 5px;
}
</style>
